package com.imooc.trie;

import java.util.TreeMap;

/**
 * Trie 多根树
 */
public class Trie {

    private class Node{
        public boolean isWord;
        public TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;
    private int size; // 单词上的数量

    public Trie() {
        root = new Node();
        size = 0;
    }

    /**
     * 查看单词数量
     * @return
     */
    public int getSize() {
        return size;
    }

    /**
     * 插入单词
     * @param word
     */
    public void add(String word) {
        Node cur = root;
        for(int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if(cur.next.get(c) == null) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }

        if(!cur.isWord) {
            cur.isWord = true;
            size ++;
        }
    }

    /**
     * 查看是否包含单词
     * @param word
     * @return
     */
    public boolean contains(String word) {
        Node cur = root;
        for(int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if(cur.next.get(c) == null)
                return false;
            cur = cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 查看单词是否是前缀
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for(int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            if(cur.next.get(c) == null) {
                return false;
            }
            cur = cur.next.get(c);
        }
        return true;
    }

    /**
     * 查询是否有某单词，例如d..g，.意味着可以匹配任意元素
     * @param word
     * @return
     */
    public boolean search(String word) {
        return match(root, word, 0);
    }

    private boolean match(Node node, String word, int index) {
        if(index == word.length()) {
            return node.isWord;
        }
        char c = word.charAt(index);
        if(c != '.') {
            if(node.next.get(c) == null) {
                return false;
            }
            return match(node.next.get(c), word, index + 1);
        }else {
            for(char nextChar: node.next.keySet())
                if(match(node.next.get(nextChar), word, index + 1))
                    return true;
            return false;
        }
    }
}
